package com.googlecode.alfrescocachingserver.util;

import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.googlecode.alfrescocachingserver.exceptions.ServiceException;

public class UriHelper
{
    private static final String JSESSIONID = ";jsessionid=";

    public static String getCompleteUri(HttpServletRequest servletRequest)
    {
        return getCompleteUri(servletRequest, true);
    }

    public static String getCompleteUri(HttpServletRequest servletRequest, boolean removeJSessionId)
    {
        String uri = servletRequest.getPathInfo();
        String queryString = servletRequest.getQueryString();
        
        if (removeJSessionId)
        {
            uri = removeJsessionidParameter(uri);
        }
        
        StringBuilder buf = new StringBuilder(uri);
        
        if (StringUtils.isNotBlank(queryString))
        {
            buf.append("?")
               .append(queryString);
        }
            
        return buf.toString();
    }
    
    public static String removeJsessionidParameter(String uri)
    {
        int jsessionidIndex = uri.indexOf(JSESSIONID);
        if (jsessionidIndex > -1)
        {
            uri = uri.substring(0, jsessionidIndex);
        }
        
        return uri;
    }
    
    public static String encode(String value)
    {
        if (StringUtils.isBlank(value))
        {
            return StringUtils.EMPTY;
        }
        
        try
        {
            return URLEncoder.encode(value, GlobalConstants.ENCODING_UTF8);
        }
        catch (Exception e)
        {
            throw new ServiceException(e);
        }
    }
}
